{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 121,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn  as nn\n",
    "import numpy as np\n",
    "import sys\n",
    "import d2lzh_pytorch as d2l"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 104,
   "metadata": {},
   "outputs": [],
   "source": [
    "def dropout(X,drop_prob):\n",
    "    X=X.float()\n",
    "    assert 0<=drop_prob<=1\n",
    "    keep_prob=1-drop_prob\n",
    "    if keep_prob==0:\n",
    "        return torch.zeros_like(X)\n",
    "    mask=(torch.rand(X.shape)<keep_prob).float()\n",
    "    return mask*X/keep_prob"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 105,
   "metadata": {},
   "outputs": [],
   "source": [
    "num_inputs,num_outputs,num_hiddens1,num_hiddens2=784,10,256,256\n",
    "W1=torch.tensor(np.random.normal(0,0.01,size=(num_inputs,num_hiddens1)),dtype=torch.float,requires_grad=True)\n",
    "b1=torch.zeros(num_hiddens1,requires_grad=True)\n",
    "W2=torch.tensor(np.random.normal(0,0.01,size=(num_hiddens1,num_hiddens2)),dtype=torch.float,requires_grad=True)\n",
    "b2=torch.zeros(num_hiddens2,requires_grad=True)\n",
    "W3 = torch.tensor(np.random.normal(0, 0.01, size=(num_hiddens2, num_outputs)), dtype=torch.float, requires_grad=True)\n",
    "b3 = torch.zeros(num_outputs, requires_grad=True)\n",
    "params=[W1,b1,W2,b2,W3,b3] "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 106,
   "metadata": {},
   "outputs": [],
   "source": [
    "drop_prob1,drop_prob2=0.2,0.5\n",
    "def net(X,is_training=True):\n",
    "    x=X.view(-1,num_inputs)\n",
    "    H1=(torch.matmul(X,W1)+b1).relu()\n",
    "    if is_training:\n",
    "        H1=dropout(H1,drop_prob1)\n",
    "    H2=(torch.matmul(H1,W2)+b2).relu()\n",
    "    if is_training:\n",
    "        H2=dropout(H2,drop_prob2)\n",
    "    return torch.matmul(H2,W3)+b3\n",
    "\n",
    "def evaluate_accuracy(data_iter,net):\n",
    "    acc_sum,n=0.0,0\n",
    "    for X,y in data_iter:\n",
    "        if  isinstance(net,torch.nn.Module):\n",
    "            net.eval()\n",
    "            acc_sum+=(net(X).argmax(dim=1)==y).float().sum.item()\n",
    "            net.train()\n",
    "        else:\n",
    "            if (\"is_training\" in net.__code__.co_varnames):\n",
    "                acc_sum+=(net(X,is_training=False).argmax(dim=1)==y).float().sum().item()\n",
    "            else:\n",
    "                acc_sum+=(net(X).argmax(dim=1)==y).float().sum().item()\n",
    "        n+=y.shape[0]\n",
    "    return acc_sum/n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 156,
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "output_type": "stream",
     "name": "stdout",
     "text": "epoch 1, loss 0.0036, train acc 0.663, test acc 0.736\nepoch 2, loss 0.0021, train acc 0.808, test acc 0.803\nepoch 3, loss 0.0018, train acc 0.830, test acc 0.822\nepoch 4, loss 0.0017, train acc 0.845, test acc 0.834\nepoch 5, loss 0.0016, train acc 0.851, test acc 0.818\n"
    }
   ],
   "source": [
    "net = nn.Sequential(\n",
    "        d2l.FlattenLayer(),\n",
    "        nn.Linear(num_inputs, num_hiddens1),\n",
    "        nn.ReLU(),\n",
    "        nn.Dropout(drop_prob1),\n",
    "        nn.Linear(num_hiddens1, num_hiddens2), \n",
    "        nn.ReLU(),\n",
    "        nn.Dropout(drop_prob2),\n",
    "        nn.Linear(num_hiddens2, 10)\n",
    "        )\n",
    "optimizer = torch.optim.SGD(net.parameters(), lr=0.5)\n",
    "d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size, None, None, optimizer)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4-final"
  },
  "orig_nbformat": 2,
  "kernelspec": {
   "name": "python37464bitbasecondab04fb1e447c742be8678bc28fb07e8e2",
   "display_name": "Python 3.7.4 64-bit ('base': conda)"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}